package com.woniu.tmsauth.controller;


import com.woniu.tmsauth.service.MenuService;
import com.woniu.tmsauth.service.UserService;
import com.woniu.tmsauth.vo.LoginDataVo;
import com.woniu.tmsauth.vo.LoginVo;
import com.woniu.tmsauth.vo.UserVo;
import com.woniu.tmscommons.entity.Menu;
import com.woniu.tmscommons.response.ResponseResult;
import com.woniu.tmscommons.utils.JWTUtil;
import feign.Headers;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private MenuService menuService;

    @PostMapping("/login")
    public ResponseResult<Object> login(@RequestBody LoginVo vo, HttpServletResponse response){
        log.debug("{}", vo);

        UserVo userInfo = userService.login(vo);
        List<Menu> menu = menuService.queryMenusByUid(userInfo.getId());
        //封装数据
        LoginDataVo data = new LoginDataVo(userInfo, menu);
        // 假设登录成功：返回用户信息、token
        String token = JWTUtil.generateToken(userInfo.getId(), userInfo.getAccount());

        // 通过相应头将token返回
        response.setHeader("authorization", token);

        return new ResponseResult<>(HttpStatus.SC_OK, "登录成功", data);
    }

    /**
     * 通过token获取到用户权限信息
     * @param token
     * @return
     */
    @GetMapping("/findPerms")
    public ResponseResult<List<String>> findPerms(@RequestHeader("authorization") String token){
        List<String> list = userService.findPerms(token);
        return new ResponseResult<>(HttpStatus.SC_OK,"success", list);
    }
}
